package com.ecloud.support.generator.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域配置
 *
 * @author LiuGangQiang Create in 2021/04/15
 */
@Configuration
public class CorsWebConfiguration {

    /**
     * 构建跨域配置
     *
     * @author LiuGangQiang Create in 2021/04/15
     * @return {@link CorsConfiguration}
     */
    private CorsConfiguration buildConfig() {
        CorsConfiguration configuration = new CorsConfiguration();
        /* 1 设置访问源地址 */
        configuration.addAllowedOrigin("*");
        /* 2 设置访问源请求头 */
        configuration.addAllowedHeader("*");
        /* 3 设置访问源请求方法 */
        configuration.addAllowedMethod("*");
        configuration.setMaxAge(3600L);
        return configuration;
    }

    /**
     * 配置跨域过滤器
     *
     * @author LiuGangQiang Create in 2021/04/15
     * @return {@link CorsFilter}
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        /* 4 对接口配置跨域设置 */
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}